'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  IconUsers,
  IconUserPlus,
  IconEdit,
  IconTrash,
  IconEye,
  IconEyeOff,
  IconSearch,
  IconRefresh,
  IconShield,
  IconBuilding,
  IconMail,
  IconPhone,
  IconSettings,
  IconCheck,
  IconX,
  IconKey,
  IconUserCheck,
  IconUserX
} from "@tabler/icons-react"
import { UserManager, User, AuthManager } from '@/lib/users'
import { UserRole, RoleDisplayNames, PermissionChecker, Permission, PermissionDisplayNames } from '@/jjk/Permissions'
import { toast } from 'sonner'

interface UserWithPermissions extends User {
  customPermissions?: Permission[]
  isActive?: boolean
}

export default function AdvancedUserManagement() {
  const [users, setUsers] = useState<UserWithPermissions[]>([])
  const [filteredUsers, setFilteredUsers] = useState<UserWithPermissions[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedRole, setSelectedRole] = useState<UserRole | 'all'>('all')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [activeTab, setActiveTab] = useState('users')

  // 新用户表单状态
  const [isCreateFormOpen, setIsCreateFormOpen] = useState(false)
  const [newUser, setNewUser] = useState({
    username: '',
    password: '',
    name: '',
    role: UserRole.NURSE,
    department: '',
    position: '',
    email: '',
    phone: '',
    customPermissions: [] as Permission[]
  })

  // 编辑用户状态
  const [editingUser, setEditingUser] = useState<UserWithPermissions | null>(null)
  const [showPassword, setShowPassword] = useState(false)

  // 权限管理状态
  const [selectedUserForPermissions, setSelectedUserForPermissions] = useState<UserWithPermissions | null>(null)

  const currentUser = AuthManager.getCurrentUser()

  // 检查权限
  const canManageUsers = currentUser?.role === UserRole.SUPER_ADMIN
  const canManagePermissions = currentUser?.role === UserRole.SUPER_ADMIN

  // 加载用户数据
  useEffect(() => {
    loadUsers()
  }, [])

  // 过滤用户
  useEffect(() => {
    let filtered = users

    // 按搜索词过滤
    if (searchTerm) {
      filtered = filtered.filter(user =>
        user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.department?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        user.position?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    }

    // 按角色过滤
    if (selectedRole !== 'all') {
      filtered = filtered.filter(user => user.role === selectedRole)
    }

    setFilteredUsers(filtered)
  }, [users, searchTerm, selectedRole])

  const loadUsers = () => {
    setIsLoading(true)
    try {
      const allUsers = UserManager.getAllUsers()
      // 扩展用户数据，添加权限信息
      const usersWithPermissions: UserWithPermissions[] = allUsers.map(user => ({
        ...user,
        customPermissions: getUserCustomPermissions(user.id),
        isActive: true // 默认激活状态
      }))
      setUsers(usersWithPermissions)
    } catch (err) {
      setError('加载用户数据失败')
      console.error('Load users error:', err)
    } finally {
      setIsLoading(false)
    }
  }

  // 获取用户自定义权限（这里可以从localStorage或API获取）
  const getUserCustomPermissions = (userId: string): Permission[] => {
    try {
      const stored = localStorage.getItem(`user_permissions_${userId}`)
      return stored ? JSON.parse(stored) : []
    } catch {
      return []
    }
  }

  // 获取用户所有权限（角色权限 + 自定义权限）
  const getUserAllPermissions = (user: UserWithPermissions): Permission[] => {
    const rolePermissions = PermissionChecker.getRolePermissions(user.role)
    const customPermissions = user.customPermissions || []
    return Array.from(new Set([...rolePermissions, ...customPermissions]))
  }

  // 保存用户自定义权限
  const saveUserCustomPermissions = (userId: string, permissions: Permission[]) => {
    try {
      localStorage.setItem(`user_permissions_${userId}`, JSON.stringify(permissions))
    } catch (err) {
      console.error('Save permissions error:', err)
    }
  }

  const handleCreateUser = () => {
    if (!canManageUsers) {
      setError('权限不足')
      return
    }

    setError('')
    setSuccess('')

    // 验证表单
    if (!newUser.username || !newUser.password || !newUser.name || !newUser.department || !newUser.position) {
      setError('请填写所有必填字段')
      return
    }

    if (!UserManager.isUsernameAvailable(newUser.username)) {
      setError('用户名已存在')
      return
    }

    // 密码强度验证
    if (newUser.password.length < 6) {
      setError('密码长度至少6位')
      return
    }

    try {
      const createdUser = UserManager.createUser(newUser)
      
      // 保存自定义权限
      if (newUser.customPermissions.length > 0) {
        saveUserCustomPermissions(createdUser.id, newUser.customPermissions)
      }
      
      setSuccess(`用户 ${createdUser.name} 创建成功`)
      toast.success(`用户 ${createdUser.name} 创建成功`)
      
      setIsCreateFormOpen(false)
      setNewUser({
        username: '',
        password: '',
        name: '',
        role: UserRole.NURSE,
        department: '',
        position: '',
        email: '',
        phone: '',
        customPermissions: []
      })
      loadUsers()
    } catch (err) {
      setError('创建用户失败')
      console.error('Create user error:', err)
    }
  }

  const handleUpdateUser = () => {
    if (!canManageUsers || !editingUser) {
      setError('权限不足或数据错误')
      return
    }

    setError('')
    setSuccess('')

    try {
      const updatedUser = UserManager.updateUser(editingUser.id, editingUser)
      if (updatedUser) {
        // 保存自定义权限
        if (editingUser.customPermissions) {
          saveUserCustomPermissions(editingUser.id, editingUser.customPermissions)
        }
        
        setSuccess(`用户 ${updatedUser.name} 更新成功`)
        toast.success(`用户 ${updatedUser.name} 更新成功`)
        setEditingUser(null)
        loadUsers()
      } else {
        setError('更新用户失败')
      }
    } catch (err) {
      setError('更新用户失败')
      console.error('Update user error:', err)
    }
  }

  const handleToggleUserStatus = (userId: string, userName: string, currentStatus: boolean) => {
    if (!canManageUsers) {
      setError('权限不足')
      return
    }

    const action = currentStatus ? '禁用' : '启用'
    if (window.confirm(`确定要${action}用户 "${userName}" 吗？`)) {
      try {
        // 这里应该调用实际的API或更新UserManager
        // 暂时更新本地状态
        setUsers(prev => prev.map(user => 
          user.id === userId ? { ...user, isActive: !currentStatus } : user
        ))
        
        setSuccess(`用户 ${userName} 已${action}`)
        toast.success(`用户 ${userName} 已${action}`)
      } catch (err) {
        setError(`${action}用户失败`)
        console.error(`Toggle user status error:`, err)
      }
    }
  }

  const handleUpdateUserPermissions = (userId: string, permissions: Permission[]) => {
    if (!canManagePermissions) {
      setError('权限不足')
      return
    }

    try {
      saveUserCustomPermissions(userId, permissions)
      
      // 更新本地状态
      setUsers(prev => prev.map(user => 
        user.id === userId ? { ...user, customPermissions: permissions } : user
      ))
      
      const user = users.find(u => u.id === userId)
      setSuccess(`用户 ${user?.name} 的权限已更新`)
      toast.success(`用户 ${user?.name} 的权限已更新`)
      
      setSelectedUserForPermissions(null)
      loadUsers()
    } catch (err) {
      setError('更新权限失败')
      console.error('Update permissions error:', err)
    }
  }

  const getUserStats = () => {
    return {
      total: users.length,
      active: users.filter(u => u.isActive !== false).length,
      inactive: users.filter(u => u.isActive === false).length,
      byRole: users.reduce((acc, user) => {
        acc[user.role] = (acc[user.role] || 0) + 1
        return acc
      }, {} as Record<UserRole, number>)
    }
  }

  const getRoleColor = (role: UserRole) => {
    switch (role) {
      case UserRole.SUPER_ADMIN:
        return 'bg-red-100 text-red-800'
      case UserRole.DEAN:
        return 'bg-purple-100 text-purple-800'
      case UserRole.DIRECTOR:
        return 'bg-blue-100 text-blue-800'
      case UserRole.DOCTOR:
        return 'bg-green-100 text-green-800'
      case UserRole.NURSE:
        return 'bg-gray-100 text-gray-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const getAllPermissions = (): Permission[] => {
    return Object.values(Permission)
  }

  const getEffectivePermissions = (user: UserWithPermissions): Permission[] => {
    const rolePermissions = PermissionChecker.getRolePermissions(user.role)
    const customPermissions = user.customPermissions || []
    
    // 合并并去重
    return Array.from(new Set([...rolePermissions, ...customPermissions]))
  }

  if (!canManageUsers) {
    return (
      <div className="text-center py-12">
        <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <IconShield className="w-8 h-8 text-red-500" />
        </div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">权限不足</h3>
        <p className="text-gray-500">只有超级管理员可以访问用户管理功能</p>
      </div>
    )
  }

  const stats = getUserStats()

  return (
    <div className="space-y-6">
      {/* 用户统计 */}
      <div className="grid grid-cols-1 md:grid-cols-6 gap-6">
        <Card className="border-blue-200 bg-blue-50">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-blue-600">总用户数</p>
                <p className="text-2xl font-bold text-blue-700">{stats.total}</p>
              </div>
              <IconUsers className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-green-200 bg-green-50">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-green-600">活跃用户</p>
                <p className="text-2xl font-bold text-green-700">{stats.active}</p>
              </div>
              <IconUserCheck className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-red-200 bg-red-50">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-red-600">禁用用户</p>
                <p className="text-2xl font-bold text-red-700">{stats.inactive}</p>
              </div>
              <IconUserX className="w-8 h-8 text-red-500" />
            </div>
          </CardContent>
        </Card>

        {Object.entries(stats.byRole).slice(0, 3).map(([role, count]) => (
          <Card key={role} className="border-gray-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">{RoleDisplayNames[role as UserRole]?.zh || role}</p>
                  <p className="text-2xl font-bold text-gray-700">{count}</p>
                </div>
                <Badge className={getRoleColor(role as UserRole)}>
                  {RoleDisplayNames[role as UserRole]?.zh || role}
                </Badge>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 操作提示 */}
      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {success && (
        <Alert className="border-green-200 bg-green-50">
          <AlertDescription className="text-green-700">{success}</AlertDescription>
        </Alert>
      )}

      {/* 标签页 */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="users">用户管理</TabsTrigger>
          <TabsTrigger value="permissions">权限管理</TabsTrigger>
        </TabsList>

        {/* 用户管理标签页 */}
        <TabsContent value="users">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>用户列表</CardTitle>
                  <CardDescription>查看和管理系统用户</CardDescription>
                </div>
                <div className="flex items-center space-x-2">
                  <Button
                    onClick={loadUsers}
                    variant="outline"
                    size="sm"
                    disabled={isLoading}
                  >
                    <IconRefresh className="w-4 h-4 mr-2" />
                    刷新
                  </Button>
                  <Button
                    onClick={() => setIsCreateFormOpen(true)}
                    size="sm"
                  >
                    <IconUserPlus className="w-4 h-4 mr-2" />
                    新建用户
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {/* 搜索和过滤 */}
              <div className="flex items-center space-x-4 mb-6">
                <div className="flex-1 relative">
                  <IconSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    placeholder="搜索用户名、姓名、科室..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                <select
                  value={selectedRole}
                  onChange={(e) => setSelectedRole(e.target.value as UserRole | 'all')}
                  className="px-3 py-2 border border-gray-300 rounded-md bg-white"
                >
                  <option value="all">所有角色</option>
                  {Object.values(UserRole).map(role => (
                    <option key={role} value={role}>
                      {RoleDisplayNames[role]?.zh || role}
                    </option>
                  ))}
                </select>
              </div>

              {/* 用户表格 */}
              <div className="border rounded-lg">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>用户信息</TableHead>
                      <TableHead>角色</TableHead>
                      <TableHead>科室职位</TableHead>
                      <TableHead>联系方式</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>权限</TableHead>
                      <TableHead>操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredUsers.map((user) => (
                      <TableRow key={user.id}>
                        <TableCell>
                          <div className="flex items-center space-x-3">
                            <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
                              {user.name.charAt(0)}
                            </div>
                            <div>
                              <div className="font-medium">{user.name}</div>
                              <div className="text-sm text-gray-500">{user.username}</div>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge className={getRoleColor(user.role)}>
                            {RoleDisplayNames[user.role]?.zh || user.role}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div>
                            <div className="font-medium">{user.department}</div>
                            <div className="text-sm text-gray-500">{user.position}</div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="space-y-1">
                            {user.email && (
                              <div className="flex items-center text-sm text-gray-600">
                                <IconMail className="w-3 h-3 mr-1" />
                                {user.email}
                              </div>
                            )}
                            {user.phone && (
                              <div className="flex items-center text-sm text-gray-600">
                                <IconPhone className="w-3 h-3 mr-1" />
                                {user.phone}
                              </div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant={user.isActive !== false ? 'default' : 'secondary'}>
                            {user.isActive !== false ? '活跃' : '禁用'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm text-gray-600">
                            {getEffectivePermissions(user).length} 个权限
                            {user.customPermissions && user.customPermissions.length > 0 && (
                              <div className="text-xs text-blue-600">
                                含 {user.customPermissions.length} 个自定义
                              </div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center space-x-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => setEditingUser(user)}
                            >
                              <IconEdit className="w-3 h-3" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => setSelectedUserForPermissions(user)}
                            >
                              <IconKey className="w-3 h-3" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleToggleUserStatus(user.id, user.name, user.isActive !== false)}
                              className={user.isActive !== false ? "text-red-600 hover:text-red-700" : "text-green-600 hover:text-green-700"}
                            >
                              {user.isActive !== false ? <IconX className="w-3 h-3" /> : <IconCheck className="w-3 h-3" />}
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {filteredUsers.length === 0 && (
                <div className="text-center py-8 text-gray-500">
                  没有找到符合条件的用户
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 权限管理标签页 */}
        <TabsContent value="permissions">
          <Card>
            <CardHeader>
              <CardTitle>权限概览</CardTitle>
              <CardDescription>查看系统中所有权限和角色分配</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* 角色权限矩阵 */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">角色权限矩阵</h3>
                  <div className="border rounded-lg p-4">
                    {Object.values(UserRole).map(role => (
                      <div key={role} className="mb-4">
                        <div className="flex items-center mb-2">
                          <Badge className={getRoleColor(role)}>
                            {RoleDisplayNames[role]?.zh || role}
                          </Badge>
                          <span className="ml-2 text-sm text-gray-600">
                            ({PermissionChecker.getRolePermissions(role).length} 个权限)
                          </span>
                        </div>
                        <div className="grid grid-cols-2 gap-1 text-xs">
                          {PermissionChecker.getRolePermissions(role).map(permission => (
                            <div key={permission} className="bg-gray-100 px-2 py-1 rounded">
                              {PermissionDisplayNames[permission]?.zh || permission}
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 用户自定义权限 */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">用户自定义权限</h3>
                  <div className="border rounded-lg p-4">
                    {users.filter(u => u.customPermissions && u.customPermissions.length > 0).length === 0 ? (
                      <div className="text-center text-gray-500 py-4">
                        暂无用户设置自定义权限
                      </div>
                    ) : (
                      users.filter(u => u.customPermissions && u.customPermissions.length > 0).map(user => (
                        <div key={user.id} className="mb-4 p-3 bg-blue-50 rounded-lg">
                          <div className="flex items-center justify-between mb-2">
                            <div className="font-medium">{user.name}</div>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setSelectedUserForPermissions(user)}
                            >
                              <IconSettings className="w-3 h-3 mr-1" />
                              管理
                            </Button>
                          </div>
                          <div className="grid grid-cols-2 gap-1 text-xs">
                            {(user.customPermissions || []).map(permission => (
                              <div key={permission} className="bg-blue-100 px-2 py-1 rounded">
                                {PermissionDisplayNames[permission]?.zh || permission}
                              </div>
                            ))}
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 创建用户对话框 */}
      {isCreateFormOpen && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <CardHeader>
              <CardTitle>创建新用户</CardTitle>
              <CardDescription>添加新的系统用户并分配权限</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="username">用户名 *</Label>
                  <Input
                    id="username"
                    value={newUser.username}
                    onChange={(e) => setNewUser({ ...newUser, username: e.target.value })}
                    placeholder="请输入用户名"
                    autoComplete="username"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="name">姓名 *</Label>
                  <Input
                    id="name"
                    value={newUser.name}
                    onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
                    placeholder="请输入姓名"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="password">密码 *</Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? 'text' : 'password'}
                    value={newUser.password}
                    onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                    placeholder="请输入密码(至少6位)"
                    autoComplete="new-password"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-0 top-0 h-full px-3"
                  >
                    {showPassword ? <IconEyeOff className="w-4 h-4" /> : <IconEye className="w-4 h-4" />}
                  </Button>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="role">角色 *</Label>
                <select
                  id="role"
                  value={newUser.role}
                  onChange={(e) => setNewUser({ ...newUser, role: e.target.value as UserRole })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md bg-white"
                >
                  {Object.values(UserRole).map(role => (
                    <option key={role} value={role}>
                      {RoleDisplayNames[role]?.zh || role}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="department">科室 *</Label>
                  <Input
                    id="department"
                    value={newUser.department}
                    onChange={(e) => setNewUser({ ...newUser, department: e.target.value })}
                    placeholder="如：内科"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="position">职位 *</Label>
                  <Input
                    id="position"
                    value={newUser.position}
                    onChange={(e) => setNewUser({ ...newUser, position: e.target.value })}
                    placeholder="如：主治医师"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  value={newUser.email}
                  onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                  placeholder="请输入邮箱地址"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="phone">电话</Label>
                <Input
                  id="phone"
                  value={newUser.phone}
                  onChange={(e) => setNewUser({ ...newUser, phone: e.target.value })}
                  placeholder="请输入电话号码"
                />
              </div>

              {/* 自定义权限选择 */}
              <div className="space-y-2">
                <Label>额外权限（可选）</Label>
                <div className="border rounded-lg p-4 max-h-48 overflow-y-auto">
                  <div className="grid grid-cols-2 gap-2">
                    {getAllPermissions().map(permission => {
                      const isRolePermission = PermissionChecker.getRolePermissions(newUser.role).includes(permission)
                      const isSelected = newUser.customPermissions.includes(permission)
                      
                      return (
                        <div key={permission} className="flex items-center space-x-2">
                          <Checkbox
                            id={`perm-${permission}`}
                            checked={isSelected}
                            disabled={isRolePermission}
                            onCheckedChange={(checked) => {
                              if (checked) {
                                setNewUser(prev => ({
                                  ...prev,
                                  customPermissions: [...prev.customPermissions, permission]
                                }))
                              } else {
                                setNewUser(prev => ({
                                  ...prev,
                                  customPermissions: prev.customPermissions.filter(p => p !== permission)
                                }))
                              }
                            }}
                          />
                          <Label
                            htmlFor={`perm-${permission}`}
                            className={`text-sm ${isRolePermission ? 'text-gray-400' : ''}`}
                          >
                            {PermissionDisplayNames[permission]?.zh || permission}
                            {isRolePermission && <span className="ml-1 text-xs">(角色自带)</span>}
                          </Label>
                        </div>
                      )
                    })}
                  </div>
                </div>
              </div>

              <div className="flex justify-end space-x-2 pt-4">
                <Button variant="outline" onClick={() => setIsCreateFormOpen(false)}>
                  取消
                </Button>
                <Button onClick={handleCreateUser}>
                  创建用户
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 编辑用户对话框 */}
      {editingUser && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <Card className="w-full max-w-md">
            <CardHeader>
              <CardTitle>编辑用户</CardTitle>
              <CardDescription>修改用户信息</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="edit-username">用户名</Label>
                  <Input
                    id="edit-username"
                    value={editingUser.username}
                    disabled
                    className="bg-gray-50"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-name">姓名</Label>
                  <Input
                    id="edit-name"
                    value={editingUser.name}
                    onChange={(e) => setEditingUser({ ...editingUser, name: e.target.value })}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit-role">角色</Label>
                <select
                  id="edit-role"
                  value={editingUser.role}
                  onChange={(e) => setEditingUser({ ...editingUser, role: e.target.value as UserRole })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md bg-white"
                >
                  {Object.values(UserRole).map(role => (
                    <option key={role} value={role}>
                      {RoleDisplayNames[role]?.zh || role}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="edit-department">科室</Label>
                  <Input
                    id="edit-department"
                    value={editingUser.department || ''}
                    onChange={(e) => setEditingUser({ ...editingUser, department: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-position">职位</Label>
                  <Input
                    id="edit-position"
                    value={editingUser.position || ''}
                    onChange={(e) => setEditingUser({ ...editingUser, position: e.target.value })}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit-email">邮箱</Label>
                <Input
                  id="edit-email"
                  type="email"
                  value={editingUser.email || ''}
                  onChange={(e) => setEditingUser({ ...editingUser, email: e.target.value })}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit-phone">电话</Label>
                <Input
                  id="edit-phone"
                  value={editingUser.phone || ''}
                  onChange={(e) => setEditingUser({ ...editingUser, phone: e.target.value })}
                />
              </div>

              <div className="flex justify-end space-x-2 pt-4">
                <Button variant="outline" onClick={() => setEditingUser(null)}>
                  取消
                </Button>
                <Button onClick={handleUpdateUser}>
                  保存更改
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 权限管理对话框 */}
      {selectedUserForPermissions && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <CardHeader>
              <CardTitle>权限管理 - {selectedUserForPermissions.name}</CardTitle>
              <CardDescription>
                角色：{RoleDisplayNames[selectedUserForPermissions.role]?.zh || selectedUserForPermissions.role}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* 角色权限（只读） */}
              <div>
                <h4 className="font-medium mb-3">角色权限（自动获得）</h4>
                <div className="grid grid-cols-2 gap-2 p-4 bg-gray-50 rounded-lg">
                  {PermissionChecker.getRolePermissions(selectedUserForPermissions.role).map(permission => (
                    <div key={permission} className="flex items-center space-x-2">
                      <IconCheck className="w-4 h-4 text-green-500" />
                      <span className="text-sm">
                        {PermissionDisplayNames[permission]?.zh || permission}
                      </span>
                    </div>
                  ))}
                </div>
              </div>

              {/* 自定义权限 */}
              <div>
                <h4 className="font-medium mb-3">额外权限</h4>
                <div className="grid grid-cols-2 gap-2 border rounded-lg p-4">
                  {getAllPermissions().map(permission => {
                    const isRolePermission = PermissionChecker.getRolePermissions(selectedUserForPermissions.role).includes(permission)
                    const isCustomSelected = (selectedUserForPermissions.customPermissions || []).includes(permission)
                    
                    if (isRolePermission) return null // 不显示角色已有的权限
                    
                    return (
                      <div key={permission} className="flex items-center space-x-2">
                        <Checkbox
                          id={`user-perm-${permission}`}
                          checked={isCustomSelected}
                          onCheckedChange={(checked) => {
                            const currentPermissions = selectedUserForPermissions.customPermissions || []
                            let newPermissions: Permission[]
                            
                            if (checked) {
                              newPermissions = [...currentPermissions, permission]
                            } else {
                              newPermissions = currentPermissions.filter(p => p !== permission)
                            }
                            
                            setSelectedUserForPermissions({
                              ...selectedUserForPermissions,
                              customPermissions: newPermissions
                            })
                          }}
                        />
                        <Label htmlFor={`user-perm-${permission}`} className="text-sm">
                          {PermissionDisplayNames[permission]?.zh || permission}
                        </Label>
                      </div>
                    )
                  })}
                </div>
              </div>

              <div className="flex justify-end space-x-2 pt-4">
                <Button 
                  variant="outline" 
                  onClick={() => setSelectedUserForPermissions(null)}
                >
                  取消
                </Button>
                <Button 
                  onClick={() => handleUpdateUserPermissions(
                    selectedUserForPermissions.id,
                    selectedUserForPermissions.customPermissions || []
                  )}
                >
                  保存权限
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  )
}